from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from meiduo_mall.libs.qq_sdk import OAuthQQHelper
from .models import OauthQQ
from meiduo_mall.utils.jwt_token import generate_jwt_token
from .serializers import QQBindSerializer
from carts.utils import merge_cookie_to_redis


class OauthQQURLView(APIView):
    def get(self, request):
        state = request.query_params.get('next')

        # 创建QQ授权对象
        oauthQQ = OAuthQQHelper(state=state)

        # 调用方法生成地址
        login_url = oauthQQ.get_qq_login_url()

        return Response({'login_url': login_url})


# class OauthQQBindView(APIView):
class OauthQQBindView(CreateAPIView):  # CreateModelMxin+GenricAPIView
    def get(self, request):
        # 接收code
        code = request.query_params.get('code')

        # 请求QQ服务器，根据code获取token
        oauthQQ = OAuthQQHelper()
        token = oauthQQ.get_access_token(code)
        # print(token)
        # return Response(token)

        # 请求QQ服务器，根据token获取openid
        openid = oauthQQ.get_openid(token)
        # return Response(openid)

        # 绑定：
        # 1.根据openid查询
        try:
            qq = OauthQQ.objects.get(openid=openid)
        except:
            # 3.如果不存在则说明初次授权，加密openid并返回
            access_token = OAuthQQHelper.generate_openid_token(openid)
            return Response({'access_token': access_token})
        else:
            # 2.如果存在则说明已经绑定，获取绑定的用户对象，生成token返回
            user = qq.user
            token = generate_jwt_token(user)

            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })

            # 非初次授权，登录成功，合并购物车
            response = merge_cookie_to_redis(request, response, user.id)

            return response

    def post(self, request, *args, **kwargs):
        # 接收
        # 验证
        # 创建对象
        # 响应
        response = super().post(request, *args, **kwargs)

        # 判断是否绑定成功
        if 'id' in response.data:
            user_id = response.data.get('id')
            # 如果绑定成功，则合并购物车数据
            response = merge_cookie_to_redis(request, response, user_id)
        # else:
        #     # 如果绑定失败则不需要合并
        #     return response

        return response

    serializer_class = QQBindSerializer
